package mpcs.view
{
	import com.google.maps.LatLng;
	
	import flash.events.Event;
	import flash.system.Capabilities;
	
	import mpcs.NotiConst;
	import mpcs.model.vo.GlobalVO;
	import mpcs.model.vo.UserVO;
	import mpcs.mylibs.core.Server;
	import mpcs.utils.ComponentManager;
	import mpcs.utils.MapManager;
	import mpcs.utils.ServerManager;
	import mpcs.utils.net.NetMonitor;
	import mpcs.utils.xml.XMLUtils;
	import mpcs.view.components.LoginForm;
	
	import mx.controls.Alert;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	/**
	 *  
	 * @author zhangzuoqiang
	 */
	public class LoginMediator extends Mediator {
		
		public static const NAME:String = "LoginMediator";
		
		private var server:Server;

		public function LoginMediator( viewComponent:LoginForm ) {
			super( NAME, viewComponent );
		}
		
		override public function onRegister():void {
			loginForm.addEventListener( LoginForm.LOGIN, onLogin );
			loginForm.addEventListener( LoginForm.NET_SETUP, onNetsetup );
			loginForm.addEventListener( LoginForm.REMEMBER, onRemember );
			loginForm.addEventListener( LoginForm.AUTO_LOGIN, onAutoLogin );
		}
		
		public function removeListeners():void {
			loginForm.addEventListener( LoginForm.LOGIN, onLogin );
			loginForm.addEventListener( LoginForm.NET_SETUP, onNetsetup );
			loginForm.addEventListener( LoginForm.REMEMBER, onRemember );
			loginForm.addEventListener( LoginForm.AUTO_LOGIN, onAutoLogin );
			
			trace("成功释放 LoginForm 中的监听器资源 ... ");
		}
		
		override public function listNotificationInterests():Array {
			return [
					NotiConst.R_LOGIN_SUCCESS,
					NotiConst.R_LOGIN_FAILED,
					NotiConst.NET_SETUP,
					NotiConst.REMEMBER,
					NotiConst.AUTO_LOGIN
				   ];
		}
		
		override public function handleNotification( note:INotification ):void {
			
			switch ( note.getName() ) {
				case NotiConst.R_LOGIN_SUCCESS:
					loginSuccHandler();// 登录成功的处理
					// 创建客户端实时接收位置数据的服务器，在此处处理的原因是，
					// 向远程服务器汇报当前连接客户端的ip，此种解决方法的弊端是如果不在同一网段无法实现该服务
					initCServer();
					break;
				case NotiConst.R_LOGIN_FAILED:
					Alert.show( "错误代码: " + note.getBody() , "登录失败");
					break;
				case NotiConst.NET_SETUP:
					break;
				case NotiConst.REMEMBER:
					break;
				case NotiConst.AUTO_LOGIN:
					break;
			}
		}
		
		// 登录成功
		private function loginSuccHandler():void {
			GlobalVO.mpcsApp.setCurrentState("logged");
			GlobalVO.mpcsApp.title = "智障人员定位监护系统";
			GlobalVO.isLogin = true;
			
			GlobalVO.mpcsApp.alwaysInFront = false;
			var screenWidth:int = Capabilities.screenResolutionX;
			var screenHeight:int = Capabilities.screenResolutionY;
			GlobalVO.mpcsApp.maxWidth = screenWidth;
			GlobalVO.mpcsApp.maxHeight = screenHeight;
			GlobalVO.mpcsApp.maximize();
		}
		
		/**
		 *  开启客户端服务器
		 */		
		private function initCServer():void{
			trace("开启客户端接收实时位置数据的服务器(打开31337端口) ... Server ... ");
			server = new Server();
			server.init();
			ServerManager.Locations = server.locations;
			ServerManager.Locations.addEventListener(CollectionEvent.COLLECTION_CHANGE, onCollectionChange);
		}
		
		// 监听有新的位置
		private function onCollectionChange(event:CollectionEvent):void{
			trace("有新的位置更新 ... LoginMediator ... onCollectionChange ... ");
			var index:int = 0;
			if (event.kind == CollectionEventKind.ADD){
				index = event.location;
			}
			// 将新的位置存入ServerManager.Locations，
			// 并且发送通知，有新的位置更新，需要在地图上转向该位置
			var previous:Object = ServerManager.Locations.getItemAt(index);
			trace("{mobile: " + previous.mobile + ", tsp: " + previous.tsp + ", lat: " + previous.lat 
				+ ", location: " + previous.location + ", lng: " + previous.lng + ", accuracy: " + previous.accuracy + "}");
			
			
//			MapManager.freshLatLng = new LatLng(ServerManager.Locations.getItemAt(index).lat, 
//				ServerManager.Locations.getItemAt(index).lng);// 更新最新的位置坐标
			var latlng:LatLng = new LatLng(ServerManager.Locations.getItemAt(index).lat, 
				ServerManager.Locations.getItemAt(index).lng);
			// 将地图中心移到最新位置
			MapManager.moveToLocation(latlng);
		}
		
		/**
		 * 发送登录请求
		 */
		private function onLogin( event:Event ):void {
			if( NetMonitor.initFlag ){
				// 已经初始化，检查当前连接状况，如果未连接，提示；如果连接，可以发送登录请求
				if(NetMonitor.CurrentState){
					sendNotification( NotiConst.NET_CONNECT_SUCCESS );
				}else{
					Alert.show( "错误信息: 当前网络无连接...", "登录失败");
				}
			}else{
				// 开始检测网络连接情况
				NetMonitor.init2();
			}
		}
		
		private function onNetsetup( event:Event ):void {
			trace("sendNotification: NET_SETUP");
			sendNotification( NotiConst.NET_SETUP );
		}
		
		private function onRemember( event:Event ):void {
			trace("sendNotification: REMEMBER");
			var isRem:Boolean = GlobalVO.mpcsApp.loginForm.remember.selected;
			if(isRem){
				GlobalVO.getPreferences().checkbox.pwd.@isremember = "true" ;
				trace(GlobalVO.getPreferences().checkbox.pwd.@isremember);
				XMLUtils.saveXMLtoFile(GlobalVO.getPreferences(), "data/preferences.xml");				
			}else{
				GlobalVO.getPreferences().checkbox.pwd.@isremember = "false" ;
				trace(GlobalVO.getPreferences().checkbox.pwd.@isremember);
				XMLUtils.saveXMLtoFile(GlobalVO.getPreferences(), "data/preferences.xml");
			}
			sendNotification( NotiConst.REMEMBER );
		}
		
		private function onAutoLogin( event:Event ):void {
			trace("sendNotification: AUTO_LOGIN");
			var isAuto:Boolean = GlobalVO.mpcsApp.loginForm.autologin.selected;
			if(isAuto){
				GlobalVO.getPreferences().checkbox.autologin.@isremember = "true" ;
				trace(GlobalVO.getPreferences().checkbox.autologin.@isremember);
				XMLUtils.saveXMLtoFile(GlobalVO.getPreferences(), "data/preferences.xml");				
			}else{
				GlobalVO.getPreferences().checkbox.autologin.@isremember = "false" ;
				trace(GlobalVO.getPreferences().checkbox.autologin.@isremember);
				XMLUtils.saveXMLtoFile(GlobalVO.getPreferences(), "data/preferences.xml");
			}
			sendNotification( NotiConst.AUTO_LOGIN );
		}
				
		private function get loginForm ():LoginForm {
			return viewComponent as LoginForm;
		}
		
		// 修改是否记住密码
		private function updateRemXML(isRem:String):void {
			
		}
		
		// 修改是否自动登录
		private function updateAutoLoginXML(isAuto:String):void {
			
		}
		
	}
}